package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Certification;
import com.gy.entity.result.ContinueEducationMaterial;
import com.gy.entity.result.Papers;
import com.gy.mapper.CertificationMapper;
import com.gy.mapper.UserMapper;
import com.gy.query.CertificationQuery;
import com.gy.result.Result;
import com.gy.service.CertificationService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class CertificationServiceImpl extends ServiceImpl<CertificationMapper, Certification> implements CertificationService {
    @Autowired
    private UploadController uploadController;
    @Autowired
    private CertificationMapper certificationMapper;
    @Autowired
    private UserServiceImpl userService;
    @Override
    public Result<PageVO<Certification>> getCertification(CertificationQuery certificationQuery) {
        Long userId = UserHolder.getUser().getUserId();

        Page<Certification> page = Page.of(certificationQuery.getPageNo(), certificationQuery.getPageSize());

        // 排序条件
        if (!certificationQuery.getSortBy().isEmpty() || certificationQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(certificationQuery.getSortBy(), certificationQuery.getIsAsc()));
        } else {
            // 为空，默认按照获得时间排序
            page.addOrder(new OrderItem("obtain_time", false));
        }

        // 构建查询条件
        LambdaQueryChainWrapper<Certification> queryWrapper = lambdaQuery().select()
                .eq(userId != null, Certification::getUserId, userId);

        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (certificationQuery.getStartDate() != null && certificationQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(certificationQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(certificationQuery.getEndDate());
                queryWrapper.between(Certification::getObtainTime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        // 执行分页查询
        Page<Certification> p = queryWrapper.page(page);

        // 封装VO结果
        PageVO<Certification> vo = new PageVO<>();
        vo.setTotal(p.getTotal());
        vo.setPages(p.getPages());
        List<Certification> records = p.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }
        return Result.success(vo);
    }

    /**
     * 根据id主键删除档案资料
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removeCertificationById(Long id) {
        Certification certification = getById(id);
        if (certification == null) {
            return Result.error("认证信息未找到");
        }

        String pdfPath = certification.getPdfPath();

        // 删除文件
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                log.error("删除文件失败，路径: {}");
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        // 删除数据库记录
        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除认证信息失败");
        }

        // 更改用户表里面的档案资料数量
        userService.decrementUserCertificateinfoCount();

        return Result.success("认证信息删除成功");
    }


    /**
     * 根据id主键查询档案信息资料
     * @param id
     * @return
     */
    @Override
    public Certification getCertificationById(Long id) {

        if (id == null) {
            return null;
        }
        return certificationMapper.selectCertificationById(id);

    }

    @Override
    public Result updateCertification(Certification certification) {
        // 参数验证
        if (certification == null) {
            return Result.error("认证信息不能为空");
        }
        if (certification.getId() == null) {
            return Result.error("认证ID不能为空");
        }

        try {
            int affectedRows = certificationMapper.updateCertification(certification);
            if (affectedRows > 0) {
                return Result.success(certification);
            } else {
                return Result.error("未找到对应的认证信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新认证信息时发生异常", e);
            return Result.error("更新认证信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveCertification(Certification certification) {
        if (certification == null) {
            log.warn("传入的认证对象为空");
            return Result.error("认证对象不能为空");
        }
        try {
            // 根据实际情况设置其他字段，这里假设没有其他需要特别设置的字段
            // 设置用户 ID
            certification.setUserId(UserHolder.getUser().getUserId());

            boolean save = certificationMapper.saveCertification(certification);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserCertificateinfoCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存认证时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getCertificationByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<Certification> certificationList = certificationMapper.selectCertificationBatchIds(Arrays.asList(ids));
            return Result.success(certificationList);
        }
        return null;
    }


}
